﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Apollo.Web;
using NHibernate;

namespace Apollo.Website
{
    public partial class BulkImportStep2 : System.Web.UI.Page, IApolloPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try {
                int bulkImportId = int.Parse(Request["Id"]);

                this.PopulatePage(bulkImportId);
            }
            catch { }
        }

        protected void PopulatePage(int bulkImportID) {
            LiteralJS.Text = "";
            LiteralColumns.Text = "";

            BulkImport import = Apollo.Application.CurrentSession.Get<BulkImport>(bulkImportID);

            LabelTo.Text = " to object of type \"" + import.Entity.Name + "\"";

            foreach (BulkImportProjection prj in Apollo.Application.CurrentSession.QueryOver<BulkImportProjection>()
                .Where(bip => bip.BulkImport.Id == bulkImportID).List()) {
                    string postBackValue = this.Request[("hiddenField" + prj.Id.ToString())];

                    string js = "\n new apolloProjection(\"#columnContainer{0}\", { entityID: " + import.Entity.Id.ToString() + ", valueContainer: \"#hiddenField{0}\"{1} });";
                    js = js.Replace("{0}", prj.Id.ToString())
                            .Replace("{1}", string.IsNullOrEmpty(postBackValue) ?
                                string.IsNullOrEmpty(prj.ProjectionPath) ? "" : ",projection:\"" + prj.ProjectionPath + "\""
                                : ",projection:\"" + postBackValue + "\"");

                LiteralJS.Text += js;


                string html = "<tr><td>{0}</td><td><div id=\"columnContainer{1}\"></div><input type=\"hidden\" name=\"hiddenField{1}\" id=\"hiddenField{1}\" value=\"{2}\" /></td></tr>";
                html = html.Replace("{0}", prj.Name)
                           .Replace("{1}", prj.Id.ToString())
                           .Replace("{2}", string.IsNullOrEmpty(postBackValue) ?
                                string.IsNullOrEmpty(prj.ProjectionPath) ? "" : prj.ProjectionPath
                                : postBackValue);
                LiteralColumns.Text += html;
            }

            LiteralJS.Text = "<script type=\"text/javascript\"> $(document).ready(function () {\n"
                + LiteralJS.Text
                + "\n});</script>";
        }

        protected void ButtonSave_Click(object sender, EventArgs e) {
            int bulkImportId = int.Parse(Request["Id"]);

            foreach (BulkImportProjection prj in Apollo.Application.CurrentSession.QueryOver<BulkImportProjection>()
                    .Where(bip => bip.BulkImport.Id == bulkImportId).List())
            {
                string postBackValue = this.Request[("hiddenField" + prj.Id.ToString())];

                prj.ProjectionPath = postBackValue;

                ITransaction tran = Apollo.Application.CurrentSession.BeginTransaction();
                try
                {
                    Apollo.Application.CurrentSession.Save(prj);

                    tran.Commit();
                }
                catch (Exception ex) {
                    MessageList.AddMessage(new ActionMessage("Failed to save \"" + prj.Name + "\": " + ex.Message, ActionMessageType.Error));

                    tran.Rollback();
                }
            }

            if (MessageList.MessagesCount <= 0) {
                #warning Set it to go to Bulk import menu
                Response.Redirect("BulkImportStep1.aspx");
            }
        }


        public int SelectedMenuItemID
        {
            get { return Apollo.Application.Meta<Apollo.MenuItem>().Single<Apollo.MenuItem>(mi => mi.Name == "Bulk import").Id; }
        }

        public int SelectedRootMenuItemId
        {
            get { return Apollo.Application.Meta<Apollo.MenuItem>().Single<Apollo.MenuItem>(mi => mi.Name == "Settings").Id; }
        }
    }
}